package com.campusbackend.controller;

import com.campusbackend.entity.CarouselImage;
import com.campusbackend.entity.Result;
import com.campusbackend.service.CarouselImageService;
import com.campusbackend.service.FileUploadService;
import com.campusbackend.utils.ResultUtil;
import com.campusbackend.vo.CarouselImageVO;
import com.campusbackend.vo.CarouselUpdateRequest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理端轮播图控制器
 *
 * @author yezi
 * @since 2025-07-29
 */
@Slf4j
@RestController
@RequestMapping("/adminUser")
@Tag(name = "管理端轮播图管理", description = "管理端轮播图相关接口")
public class CarouselController {

    @Autowired
    private CarouselImageService carouselImageService;

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 获取轮播图列表
     * @return 轮播图列表
     */
    @GetMapping("/carousel")
    @Operation(summary = "获取轮播图列表", description = "获取所有轮播图，按位置排序")
    public Result<List<CarouselImageVO>> getCarouselImages() {
        log.info("获取轮播图列表请求");
        
        try {
            List<CarouselImage> carouselImages = carouselImageService.getAllCarouselImages();
            
            // 转换为VO对象
            List<CarouselImageVO> carouselImageVOs = carouselImages.stream()
                    .map(carouselImage -> {
                        CarouselImageVO vo = new CarouselImageVO();
                        BeanUtils.copyProperties(carouselImage, vo);
                        return vo;
                    })
                    .collect(Collectors.toList());
            
            return ResultUtil.success(carouselImageVOs);
        } catch (Exception e) {
            log.error("获取轮播图列表异常", e);
            return ResultUtil.fail("获取轮播图列表时发生错误");
        }
    }

    /**
     * 更新轮播图
     * @param position 轮播图位置 (1-6)
     * @param request 更新请求
     * @return 更新后的轮播图
     */
    @PutMapping("/carousel/{position}")
    @Operation(summary = "更新轮播图", description = "根据位置更新轮播图信息")
    public Result<CarouselImageVO> updateCarouselImage(
            @Parameter(description = "轮播图位置 (1-6)", required = true)
            @PathVariable Integer position,
            @RequestBody CarouselUpdateRequest request) {
        
        log.info("更新轮播图请求 - position: {}, request: {}", position, request);
        
        try {
            // 验证position范围
            if (position < 1 || position > 6) {
                return ResultUtil.fail("参数错误：position 必须在 1-6 范围内");
            }

            CarouselImage updatedCarousel = carouselImageService.updateCarouselImage(
                    position, 
                    request.getImageUrl(), 
                    request.getImageName(), 
                    request.getIsActive()
            );

            // 转换为VO对象
            CarouselImageVO vo = new CarouselImageVO();
            BeanUtils.copyProperties(updatedCarousel, vo);

            return ResultUtil.success(vo);
        } catch (IllegalArgumentException e) {
            log.warn("更新轮播图参数错误", e);
            return ResultUtil.fail(e.getMessage());
        } catch (Exception e) {
            log.error("更新轮播图异常", e);
            return ResultUtil.fail("更新轮播图时发生错误");
        }
    }

    /**
     * 上传轮播图图片
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping("/carousel/upload")
    @Operation(summary = "上传轮播图图片", description = "上传轮播图图片文件，支持jpg、jpeg、png、gif、webp格式，最大10MB")
    public Result<Map<String, Object>> uploadCarouselImage(@RequestParam("file") MultipartFile file) {
        log.info("收到轮播图图片上传请求 - 文件名: {}, 文件大小: {} bytes",
                file.getOriginalFilename(), file.getSize());

        try {
            Map<String, Object> result = fileUploadService.uploadImage(file);

            if ((Boolean) result.get("success")) {
                return ResultUtil.success(result);
            } else {
                return ResultUtil.fail((String) result.get("message"));
            }
        } catch (Exception e) {
            log.error("轮播图图片上传异常", e);
            return ResultUtil.fail("图片上传时发生错误");
        }
    }
}
